﻿function Categories() {
    var self = this;
    this.collection = ko.observableArray();

    this.successMessage = ko.observable();
    this.errors = ko.observableArray();
    this.errorMessage = ko.computed({
        read: function () {
            var html = '';
            if (this.errors().length > 0)
                html += this.errors()[0];
            if (this.errors().length > 1) {
                html += "<ul>"
                for (var idx = 1; idx < this.errors().length; idx++)
                    html += "<li>" + this.errors()[idx] + "</li>";
                html += "</ul>";
            }
            return html;
        },
        write: function (value) {
            this.errors.removeAll();
            this.errors.push(value);
        },
        owner: this
    });

    this.addEnable = ko.observable(true);

    this.loadJson = function (data) {
        for (var idx = 0; idx < data.length; idx++) {
            var elem = data[idx];
            var item = new Category(this);
            item.isOdd(idx % 2 == 0);
            item.load(elem);
            this.collection.push(item);
        }
    }

    this.redoOdd = function () {
        for (var idx = 0; idx < this.collection().length; idx++) {
            var item = this.collection()[idx];
            item.isOdd(idx % 2 == 0);
        }
    }

    this.add = function () {
        var item = new Category(this);
        item.isEdit(true);
        item.isNew(true);
        this.collection.push(item);
        this.addEnable(false);
    }

    this.get = function (id) {
        for (var idx = 0; idx < this.collection().length; idx++) {
            if (this.collection()[idx].name() == id)
                return this.collection()[idx];
        }
    }

    this.sort = function () {
        this.collection.sort(function (left, right) {
            return left.order() < right.order() ? -1 : 1;
        });
    }

    this.remove = function (removeItem) {
        this.collection.remove(function (item) { return item.name() == removeItem.name() });
    }

    this.reorder = function () {
        var order = '';
        $('ul#reorder li').each(function () {
            order = order + $(this).attr('id') + ',';
        });
        
        var url = appPath + 'Category/Reorder/'
        var input = {
            order: order
        };
        $.post(url, input, function (data) {
            if (data.Result) {
                $('ul#reorder li').each(function (index) {
                    var id = $(this).attr('id');
                    var cat = self.get(id);
                    cat.order(index + 1);
                });
                self.sort();
                self.redoOdd();
            }
        });
    }
}